<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>添加商品</title>
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <legend>添加商品</legend>
      <div class="form-group">
        <label for="">商品名</label>
        <input
          type="text"
          class="form-control"
          id="pname"
          placeholder="请输入商品名"
        />
      </div>
      <div class="form-group">
        <label for="">价格</label>
        <input
          type="text"
          class="form-control"
          id="pprice"
          placeholder="请输入商品价格"
        />
      </div>
      <div class="form-group">
        <label for="">描述</label>
        <textarea
          class="form-control"
          id="pdesc"
          cols="30"
          rows="10"
          placeholder="请输入商品描述"
        ></textarea>
      </div>
      <div class="form-group">
        <label for="">选择图片</label>
        <input
          type="file"
          class="form-control"
          id="imgIpt"
          placeholder="请添加商品图片"
        />
        <img src="" alt="" id="img" style="width: 150px; height: 150px" />
      </div>
      <button type="submit" class="btn btn-primary">添加商品</button>
    </div>
  </body>
  <script>
    //上传图片
    let imgUrl = "";
    $("#imgIpt").change(function () {
      let formdata = new FormData(); //文件上传使用FormData对象
      formdata.append("avatar", $("#imgIpt")[0].files[0]);
      $.ajax({
        url: "/profile",
        type: "post",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (res) {
          console.log(res);
          $("#img").attr("src", "http://localhost:8888/" + res.path);
          console.log($("#img").attr("src"));
          imgUrl = "http://localhost:8888/" + res.path;
        },
      });
    });

    //添加商品。使用接口 /addmyshop
    $("button").click(function () {
      let pname = $("#pname").val();
      let pprice = $("#pprice").val();
      let pdesc = $("#pdesc").val();
      // let pimg = $("#pimg").val();
      let uid = localStorage.getItem("uid");
      //判断uid是否存在很重要，要进行判断，如果传过去的数据中没有uid或为空，就不能往数据库里存入
      let params = {
        pname: pname,
        pprice: pprice,
        pdesc: pdesc,
        pimg: imgUrl,
        uid: uid,
      };
      console.log(params);
      if (params.uid) {
        $.ajax({
          url: "/addmyshop",
          type: "post",
          data: params,
          success: (res) => {
            console.log(res);
            alert(res.msg);
            location.href = "/myshop";
          },
        });
      } else {
        alert("请检查是否登录");
      }
    });
  </script>
</html>
